//
//  IATokenManager.m
//  VoiceClass
//
//  Created by caoxiaobo on 2017/12/10.
//  Copyright © 2017年 YRX. All rights reserved.
//

#import "IATokenManager.h"
#import "Definition.h"
#import "AFNetworking.h"
#import "MJExtension.h"

static NSString * const kTokenHTTPPrefix = @"https://aip.baidubce.com/oauth/2.0/token";
static NSString * const kBaiduGrantType = @"client_credentials";
static NSString * const kBaiduAppKey = @"uDCpCer3sgkczshn1F779rF7";
static NSString * const kBaiduSecretKey = @"UrMXSLu6oPtOGnMNxaE1wRqpNhaqQQ5U";

@implementation IAToken

+ (instancetype)shareToken {
    static IAToken *aToken = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        aToken = [[IAToken alloc] init];
    });
    return aToken;
}

MJExtensionCodingImplementation

@end

@implementation IATokenManager

+ (NSString *)filePath {
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    return [documentPath stringByAppendingString:@"/TokenFile"];
}

+ (IAToken *)readToken {
    IAToken *token = [NSKeyedUnarchiver unarchiveObjectWithFile:[self filePath]];
    if (token) {
        [self setupIAToken:token];
    }
    return token;
}

+ (void)requestTokenHanler:(void (^)(BOOL result, IAToken *token))handler {
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSDictionary *dictionary =@{@"grant_type" : kBaiduGrantType,
                                @"client_id" : kBaiduAppKey,
                                @"client_secret" : kBaiduSecretKey
                                };
    [manager POST:kTokenHTTPPrefix
       parameters:dictionary
         progress:nil
          success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
              if ([responseObject isKindOfClass:[NSDictionary class]]) {
                  IAToken *iaToken = [IAToken mj_objectWithKeyValues:responseObject context:nil];
                  if (iaToken.expires_in.length > 0) {
                      iaToken.expires_time = [NSDate dateWithTimeIntervalSinceNow:iaToken.expires_in.doubleValue];
                  }
                  [self setupIAToken:iaToken];
                  BOOL suc = [NSKeyedArchiver archiveRootObject:iaToken toFile:[self filePath]];
                  if (suc) {
                      NSLog(@"archive user token success");
                  } else {
                      NSLog(@"request user token success, but archived failed");
                  }
                  
                  if (handler) {
                      handler(suc, iaToken);
                  }
              } else {
                  if (handler) {
                      handler(NO, nil);
                  }
              }
          }
          failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
              NSLog(@"request user token failed");
              if (handler) {
                  handler(NO, nil);
              }
          }];
}

+ (void)setupIAToken:(IAToken *)token {
    IAToken *sharedToken = [IAToken shareToken];
    sharedToken.access_token = token.access_token;
    sharedToken.refresh_token = token.refresh_token;
    sharedToken.scope = token.scope;
    sharedToken.expires_in = token.expires_in;
    sharedToken.session_secret = token.session_secret;
    sharedToken.session_key = token.session_key;
    sharedToken.scope = token.scope;
    sharedToken.expires_time = token.expires_time;
}

@end
